package com.dfsoft.controller;

import com.dfsoft.config.ViewFileConfig;
import com.dfsoft.exception.BaseBusinessException;
import com.dfsoft.libreoffice.OfficeConvertToPdfService;
import com.dfsoft.util.FileUtils;
import com.dfsoft.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author yuandf
 */
@Slf4j
@RestController
public class FileController {

    @Autowired
    private OfficeConvertToPdfService officeConvertToPdfService;

    @Autowired
    private ViewFileConfig viewFileConfig;

//    @GetMapping("/onlinePreview/bak")
    public void onlinePreviewBak(HttpServletResponse response, @RequestParam String url) throws Exception {
        String fileName = WebUtils.getUrlParameterReg(url, "fullfilename");
        String realName = WebUtils.getUrlParameterReg(url, "realname");
//        log.info(">>> file.getName()：【{}】，file.getOriginalFilename()：【{}】，file.getSize()：【{}】",
//                file.getName(), fileName, file.getSize());

        final String fileSuffix = StringUtils.substringAfterLast(fileName, ".");
        String fileUrl = new String(Base64.decodeBase64(url), StandardCharsets.UTF_8);
        try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            try {
                // 文件扩展名匹配了转换服务内的扩展名，则调用转换服务进行转换pdf
                // 如果DocumentFormatEnum.valueOf()找不到时抛出异常：IllegalArgumentException
                final OfficeConvertToPdfService.DocumentFormatEnum documentFormatEnum = OfficeConvertToPdfService.DocumentFormatEnum.valueOf(fileSuffix.toUpperCase());
                if (!Objects.isNull(documentFormatEnum)) {
                    try (InputStream inputStream = getInputStreamByUrl(fileUrl)) {
                        officeConvertToPdfService.convert(inputStream, bos, fileSuffix);
                    }
                }
            } catch (IllegalArgumentException e) {
                bos.reset();
                try (InputStream inputStream = getInputStreamByUrl(fileUrl)) {
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = inputStream.read(buffer)) > 0) {
                        bos.write(buffer, 0, length);
                    }
//                    bos.write(file.getBytes(), 0, file.getBytes().length);
                }
            }
            bos.close();
            final byte[] bytes = bos.toByteArray();
            response.setCharacterEncoding("UTF-8");
            // response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getOriginalFilename().getBytes("UTF-8"), "ISO-8859-1")); //
            response.setHeader("Content-Length", String.valueOf(bytes.length));
            ServletOutputStream out = response.getOutputStream();
            out.write(bytes);
            out.flush();
        }
    }

    @GetMapping("/onlinePreview")
    public void onlinePreview(HttpServletRequest request, HttpServletResponse response, @RequestParam String url) throws Exception {
        String fileUrl = new String(Base64.decodeBase64(url), StandardCharsets.UTF_8);
        String fileName = WebUtils.getUrlParameterReg(fileUrl, "fullfilename");
        String realName = WebUtils.getUrlParameterReg(fileUrl, "realname");

        try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            if(StringUtils.isBlank(fileName)){
                throw new BaseBusinessException(500,"缺少文件名");
            }
            final String fileSuffix = StringUtils.substringAfterLast(fileName, ".");
            String realPath = viewFileConfig.getPath() + File.separator + realName + "." + fileSuffix;

            try {
                if(FileUtils.existsFile(realPath)){
                    try (InputStream inputStream = new FileInputStream(realPath)){
                        FileUtils.inputStreamWriteOutputStream(bos,inputStream);
                    }
                }else{
                    if(StringUtils.equals(fileSuffix.toUpperCase(),"pdf".toUpperCase())){
                        try (InputStream inputStream = getInputStreamByUrl(fileUrl)) {
                            FileUtils.inputStreamWriteOutputStream(bos,inputStream);
                            inputStream.reset();
                            FileUtils.inputStreamWriteToLocal(realPath,inputStream);
                        }
                    }else{
                        // 文件扩展名匹配了转换服务内的扩展名，则调用转换服务进行转换pdf
                        // 如果DocumentFormatEnum.valueOf()找不到时抛出异常：IllegalArgumentException
                        final OfficeConvertToPdfService.DocumentFormatEnum documentFormatEnum =
                                OfficeConvertToPdfService.DocumentFormatEnum.valueOf(fileSuffix.toUpperCase());
                        if (!Objects.isNull(documentFormatEnum)) {
                            realPath = viewFileConfig.getPath() + File.separator + realName + ".pdf";
                            if(FileUtils.existsFile(realPath)){
                                try (InputStream inputStream = new FileInputStream(realPath)){
                                    FileUtils.inputStreamWriteOutputStream(bos,inputStream);
                                }
                            }else{
                                try (InputStream inputStream = getInputStreamByUrl(fileUrl)) {
                                    officeConvertToPdfService.convert(inputStream, bos, fileSuffix);
                                    bos.reset();
                                    FileUtils.byteArrayOutputStreamWriteToLocal(realPath,bos);
                                }
                            }
                        }
                    }
                }

            } catch (IllegalArgumentException e) {
                bos.reset();
                try (InputStream inputStream = getInputStreamByUrl(fileUrl)) {
                    FileUtils.inputStreamWriteOutputStream(bos,inputStream);
                    inputStream.reset();
                    FileUtils.inputStreamWriteToLocal(realPath,inputStream);
                }
            }
            bos.close();
            final byte[] bytes = bos.toByteArray();
            response.setCharacterEncoding("UTF-8");
            // response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getOriginalFilename().getBytes("UTF-8"), "ISO-8859-1")); //
            response.setHeader("Content-Length", String.valueOf(bytes.length));
            ServletOutputStream out = response.getOutputStream();
            out.write(bytes);
            out.flush();
        }catch (BaseBusinessException e){
            request.setAttribute("errorInfo",e.getMessage());
            request.getRequestDispatcher("/error/info").forward(request,response);
        }catch (Exception e){
            request.setAttribute("errorInfo","文件读取失败");
            request.getRequestDispatcher("/error/info").forward(request,response);
        }
    }

    @GetMapping("/onlinePreview/temp")
    public void onlinePreviewTemp(HttpServletRequest request, HttpServletResponse response, @RequestParam String url) throws Exception {
        String fileUrl = new String(Base64.decodeBase64(url), StandardCharsets.UTF_8);
        String fileName = WebUtils.getUrlParameterReg(fileUrl, "fullfilename");
        String realName = WebUtils.getUrlParameterReg(fileUrl, "realname");
        try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            if(StringUtils.isBlank(fileName)){
                throw new BaseBusinessException(500,"缺少文件名");
            }
            final String fileSuffix = StringUtils.substringAfterLast(fileName, ".");
            String realPath = viewFileConfig.getTempPath() + File.separator + realName + "." + fileSuffix;
            try {
                if(FileUtils.existsFile(realPath)){
                    try (InputStream inputStream = new FileInputStream(realPath)){
                        FileUtils.inputStreamWriteOutputStream(bos,inputStream);
                    }
                }else{
                    if(StringUtils.equals(fileSuffix.toUpperCase(),"pdf".toUpperCase())){
                        try (InputStream inputStream = getInputStreamByUrl(fileUrl)) {
                            FileUtils.inputStreamWriteOutputStream(bos,inputStream);
                            inputStream.reset();
                            FileUtils.inputStreamWriteToLocal(realPath,inputStream);
                        }
                    }else{
                        // 文件扩展名匹配了转换服务内的扩展名，则调用转换服务进行转换pdf
                        // 如果DocumentFormatEnum.valueOf()找不到时抛出异常：IllegalArgumentException
                        final OfficeConvertToPdfService.DocumentFormatEnum documentFormatEnum =
                                OfficeConvertToPdfService.DocumentFormatEnum.valueOf(fileSuffix.toUpperCase());
                        if (!Objects.isNull(documentFormatEnum)) {
                            realPath = viewFileConfig.getTempPath() + File.separator + realName + ".pdf";
                            if(FileUtils.existsFile(realPath)){
                                try (InputStream inputStream = new FileInputStream(realPath)){
                                    FileUtils.inputStreamWriteOutputStream(bos,inputStream);
                                }
                            }else{
                                try (InputStream inputStream = getInputStreamByUrl(fileUrl)) {
                                    officeConvertToPdfService.convert(inputStream, bos, fileSuffix);
                                    bos.reset();
                                    FileUtils.byteArrayOutputStreamWriteToLocal(realPath,bos);
                                }
                            }
                        }
                    }
                }

            } catch (IllegalArgumentException e) {
                bos.reset();
                try (InputStream inputStream = getInputStreamByUrl(fileUrl)) {
                    FileUtils.inputStreamWriteOutputStream(bos,inputStream);
                    inputStream.reset();
                    FileUtils.inputStreamWriteToLocal(realPath,inputStream);
                }
            }
            bos.close();
            final byte[] bytes = bos.toByteArray();
            response.setCharacterEncoding("UTF-8");
            // response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getOriginalFilename().getBytes("UTF-8"), "ISO-8859-1")); //
            response.setHeader("Content-Length", String.valueOf(bytes.length));
            ServletOutputStream out = response.getOutputStream();
            out.write(bytes);
            out.flush();
        }catch (BaseBusinessException e){
            request.setAttribute("errorInfo",e.getMessage());
            request.getRequestDispatcher("/error/info").forward(request,response);
        }catch (Exception e){
            request.setAttribute("errorInfo","文件读取失败");
            request.getRequestDispatcher("/error/info").forward(request,response);
        }
    }

    @PostMapping("/file/upload")
    public void upload(MultipartFile file, HttpServletResponse response) throws Exception {
        log.info(">>> file.getName()：【{}】，file.getOriginalFilename()：【{}】，file.getSize()：【{}】", file.getName(), file.getOriginalFilename(), file.getSize());
        final String fileSuffix = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");

        try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            try {
                // 文件扩展名匹配了转换服务内的扩展名，则调用转换服务进行转换pdf
                // 如果DocumentFormatEnum.valueOf()找不到时抛出异常：IllegalArgumentException
                final OfficeConvertToPdfService.DocumentFormatEnum documentFormatEnum = OfficeConvertToPdfService.DocumentFormatEnum.valueOf(fileSuffix.toUpperCase());
                if (!Objects.isNull(documentFormatEnum)) {
                    officeConvertToPdfService.convert(file.getInputStream(), bos, fileSuffix);
                }
            } catch (IllegalArgumentException e) {
                bos.reset();
                try (InputStream inputStream = file.getInputStream()) {
                    //byte[] buffer = new byte[1024];
                    //int length;
                    //while ((length = inputStream.getInputStream().read(buffer)) > 0) {
                    //    bos.write(buffer, 0, length);
                    //}
                    bos.write(file.getBytes(), 0, file.getBytes().length);
                }
            }
            bos.close();
            final byte[] bytes = bos.toByteArray();
            response.setCharacterEncoding("UTF-8");
            // response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getOriginalFilename().getBytes("UTF-8"), "ISO-8859-1")); //
            response.setHeader("Content-Length", String.valueOf(bytes.length));
            ServletOutputStream out = response.getOutputStream();
            out.write(bytes);
            out.flush();
        }
    }

    @GetMapping("/convertFile/temp")
    public void convertFileTemp(@RequestParam String url) throws Exception {
        String fileUrl = new String(Base64.decodeBase64(url), StandardCharsets.UTF_8);
        String fileName = WebUtils.getUrlParameterReg(fileUrl, "fullfilename");
        String realName = WebUtils.getUrlParameterReg(fileUrl, "realname");

        try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            if(StringUtils.isBlank(fileName)){
                throw new BaseBusinessException(500,"缺少文件名");
            }
            final String fileSuffix = StringUtils.substringAfterLast(fileName, ".");
            String realPath = viewFileConfig.getTempPath() + File.separator + realName + "." + fileSuffix;
            try {
                if(!FileUtils.existsFile(realPath)){
                    if(StringUtils.equals(fileSuffix.toUpperCase(),"pdf".toUpperCase())){
                        try (InputStream inputStream = getInputStreamByUrl(fileUrl)) {
                            FileUtils.inputStreamWriteToLocal(realPath,inputStream);
                        }
                    }else{
                        // 文件扩展名匹配了转换服务内的扩展名，则调用转换服务进行转换pdf
                        // 如果DocumentFormatEnum.valueOf()找不到时抛出异常：IllegalArgumentException
                        final OfficeConvertToPdfService.DocumentFormatEnum documentFormatEnum =
                                OfficeConvertToPdfService.DocumentFormatEnum.valueOf(fileSuffix.toUpperCase());
                        if (!Objects.isNull(documentFormatEnum)) {
                            realPath = viewFileConfig.getTempPath() + File.separator + realName + ".pdf";
                            if(!FileUtils.existsFile(realPath)){
                                try (InputStream inputStream = getInputStreamByUrl(fileUrl)) {
                                    officeConvertToPdfService.convert(inputStream, bos, fileSuffix);
                                    bos.reset();
                                    FileUtils.byteArrayOutputStreamWriteToLocal(realPath,bos);
                                }
                            }
                        }
                    }
                }

            } catch (IllegalArgumentException e) {
                bos.reset();
                try (InputStream inputStream = getInputStreamByUrl(fileUrl)) {
                    FileUtils.inputStreamWriteToLocal(realPath,inputStream);
                }
            }
        }
    }

    @GetMapping("/convertFile")
    public void convertFile(@RequestParam String url) throws Exception {
        String fileUrl = new String(Base64.decodeBase64(url), StandardCharsets.UTF_8);
        String fileName = WebUtils.getUrlParameterReg(fileUrl, "fullfilename");
        String realName = WebUtils.getUrlParameterReg(fileUrl, "realname");

        try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            if(StringUtils.isBlank(fileName)){
                throw new BaseBusinessException(500,"缺少文件名");
            }
            final String fileSuffix = StringUtils.substringAfterLast(fileName, ".");
            String realPath = viewFileConfig.getPath() + File.separator + realName + "." + fileSuffix;
            try {
                if(!FileUtils.existsFile(realPath)){
                    if(StringUtils.equals(fileSuffix.toUpperCase(),"pdf".toUpperCase())){
                        try (InputStream inputStream = getInputStreamByUrl(fileUrl)) {
                            FileUtils.inputStreamWriteToLocal(realPath,inputStream);
                        }
                    }else{
                        // 文件扩展名匹配了转换服务内的扩展名，则调用转换服务进行转换pdf
                        // 如果DocumentFormatEnum.valueOf()找不到时抛出异常：IllegalArgumentException
                        final OfficeConvertToPdfService.DocumentFormatEnum documentFormatEnum =
                                OfficeConvertToPdfService.DocumentFormatEnum.valueOf(fileSuffix.toUpperCase());
                        if (!Objects.isNull(documentFormatEnum)) {
                            realPath = viewFileConfig.getPath() + File.separator + realName + ".pdf";
                            if(!FileUtils.existsFile(realPath)){
                                try (InputStream inputStream = getInputStreamByUrl(fileUrl)) {
                                    officeConvertToPdfService.convert(inputStream, bos, fileSuffix);
                                    bos.reset();
                                    FileUtils.byteArrayOutputStreamWriteToLocal(realPath,bos);
                                }
                            }
                        }
                    }
                }

            } catch (IllegalArgumentException e) {
                bos.reset();
                try (InputStream inputStream = getInputStreamByUrl(fileUrl)) {
                    FileUtils.inputStreamWriteToLocal(realPath,inputStream);
                }
            }
        }
    }

    private InputStream getInputStreamByUrl(String strUrl) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(20 * 1000);
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(conn.getInputStream(), output);
            return new ByteArrayInputStream(output.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseBusinessException(500,"文件URL读取失败");
//            logger.error("getInputStreamByUrl 异常,exception is {}", e);
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {
            }
        }
    }
}
